package com.yl.users.services.impl

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.users.entity.CompanyPermissionsView
import com.yl.users.mapper.CompanyPermissionsViewMapper
import com.yl.users.mapper.SysCompanyPermissionsMapper
import com.yl.users.services.ICompanyPermViewService
import com.yl.users.services.ICompanyUserService
import org.springframework.stereotype.Service
import java.util.*

@Service
class CompanyPermViewServiceImpl(
	private val companyPermissionsViewMapper: CompanyPermissionsViewMapper
): ICompanyPermViewService {

	private lateinit var iCompanyUserService: ICompanyUserService

	override fun getCompanyPermViewDetail(id: Long): CompanyPermissionsView? {
		return companyPermissionsViewMapper.selectById(id)
	}

	override fun updateCompanyPermView(companyPermissionsView: CompanyPermissionsView): ResponseBody {

		val view = companyPermissionsViewMapper.selectById(companyPermissionsView.id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND
		)
		if (view.createType == 1) {
			companyPermissionsView.permissionsId = null
			companyPermissionsView.permissionsType = null
		}
		if (companyPermissionsView.permissionsName.isNullOrEmpty()) {
			return returnError(ErrorCode.PARAM_EMPTY, "请输入名称")
		}
		if (companyPermissionsView.parentId == null) {
			companyPermissionsView.parentId = 0
		}
		companyPermissionsView.updateTime = Date()
		companyPermissionsViewMapper.updateById(companyPermissionsView)
		return returnSuccess()
	}

	override fun delCompanyPermView( id: Long): ResponseBody {
		val view = companyPermissionsViewMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if (view.createType == 1) {
			return returnError(ErrorCode.DATA_DELETE_FAILED, "该权限支持删除")
		}
		val selectCount = companyPermissionsViewMapper.selectCount(
			Wrappers.query<CompanyPermissionsView?>().eq("parent_id", view.id).eq("company_id", view.companyId)
		)
		if (selectCount != 0) {
			return returnError(ErrorCode.DATA_DELETE_FAILED, "该权限存在子级目录")
		}
		companyPermissionsViewMapper.deleteById(id)
		iCompanyUserService.cleanCacheByCompany(view.companyId)
		return returnSuccess()
	}

	override fun bindParentId(viewId:Long,parentId:Long):ResponseBody{
		val companyPermViewDetail = getCompanyPermViewDetail(viewId)?:return returnError(ErrorCode.OPERATION_DATA_ERROR)
		if(parentId != 0L){
			getCompanyPermViewDetail(viewId)?:return returnError(ErrorCode.OPERATION_DATA_ERROR)
		}
		companyPermViewDetail.parentId = parentId
		companyPermissionsViewMapper.updateById(companyPermViewDetail)
		return returnSuccess()
	}
}